<template>
<div class="attrGroupWrapper ui segment" v-if="show">
  <p>
    <button class="ui circular icon button tiny" @click.prevent="addGroup()">添加Tab<i class="icon plus"></i>
      </button>
  </p>
  <draggable element="div" v-if="attr.length>0" v-model="attr" :options="dragOptions" :move="onMove" @start="isDragging=true" @end="isDragging=false" @change="hlChange">
    <transition-group type="transition" :name="'flip-list'" tag="div">

      <div v-for="(val,index) in attr" class="ui compact message" :key="index">
        <sort_item :info="val" model="Attr"></sort_item>
      </div>
    </transition-group>
  </draggable>

  <div v-if="group.length>0" v-for="(g,gind) in group" class="ui vertical stackable menu">
    <div class="header item"><i class="icon remove circle" @click="toRemove(gind)"></i><input type="text" v-model="group[gind]" @dblclick="editGroup(gind)">
    </div>
    <draggable element="div" v-model="attr_group[gind]" :options="dragOptions" :move="onMove" @start="isDragging=true" @end="isDragging=false" @change="hlChange">
      <transition-group type="transition" :name="'flip-list'" tag="div">
        <sort_item :info="val" model="Attr" v-for="(val,index) in attr_group[gind]" class="item" :key="index">
          <i class="icon remove" @click.stop.prevent="removeItem(gind,index)"></i>
        </sort_item>
      </transition-group>
    </draggable>
  </div>
</div>
</template>

<script type="text/ecmascript-6">
import tool from 'src/util/tool';
import util from '_util/index';
import logic from '_logic';
import RP from 'src/util/common/attr_sort';
import draggable from 'vuedraggable'

import sort_item from 'components/common/sort_item'

const IMGPRE = tool.IMGPRE

export default {
  data() {
    return {
      // vals: []
      plist: [],
      attr: [],
      // attr2: [],
      attr_group: [],
      group: ['基础'],
      group_str: '',
      tab_title: [],
      tab_title_str: '',
      attr_group_str: '',
      editable: true,
      isDragging: false,
      show: false,
      inner_filtered: false,
      delayedDragging: false
    }
  },
  components: {
    draggable,sort_item
  },
  methods: {
    removeItem(gind, index) {
      let removed = this.attr_group[gind].splice(index, 1)[0]
      if (removed.id != -1)
        this.attr.push(removed)
      if (this.attr_group[gind].length == 0) {
        this.group.splice(gind, 1)
        this.tab_title.splice(gind, 1)
        this.attr_group.splice(gind, 1)
      }
    },
    toRemove(index) {
      this.group.splice(index, 1);
      this.tab_title.splice(index, 1);
      let removed = this.attr_group.splice(index, 1)
      if (removed[0].length > 0) {
        removed[0].forEach(item => {
          if (item.id != -1)
            this.attr.push(item)
        });
      }

    },
    filter_attr(attr) {
      if(!attr) {
        this.inner_filtered=true;
      }
      attr = attr || this.attr_group_str
      let has = JSON.parse(attr)
      let tmp = [];
      tmp = has.reduce((coll, item) => {
        let rs = coll.concat(item)
        return rs;
      }, tmp);
      this.attr = this.attr.filter(item => {
        return !tmp.contains(item.id)
      });
    },
    toAddAttrGroup() {
      RP.yes_event(this)
    },
    showPop() {
      let eventVue = util.store.get(this,'eventVue');
      let info = {
        mid: 9,
        yes_event: 'toAddAttrGroup'
      }
      eventVue.$emit('setModal')
      eventVue.$emit('setModalContent', info)
    },
    pro_attr_group_str() {
      let hled = this.attr_group.map(group => {
        return group.map(field => {
          return field.id
        })
      })
      this.attr_group_str = JSON.stringify(hled)
      this.setEditvo('attr_group_str')
    },
    pro_group_str() {
      this.group_str = JSON.stringify(this.group)
      this.setEditvo('group_str')
    },
    pro_tab_title_str() {
      this.tab_title_str = JSON.stringify(this.tab_title)
      this.setEditvo('tab_title_str')
    },
    editGroup(ind) {
      util.store.commit(this,'setModalOp', 'update');
      let vo = {tab_title: this.tab_title[ind], group_name: this.group[ind]};
      logic.edit.showEditPop(this, 9, () => {
        let newvo = util.store.get(this, 'editVoModal');
        this.$set(this.tab_title, ind, newvo.tab_title);
        this.$set(this.group, ind, newvo.group_name);
        util.showMypop(this,'success', '修改成功！');
      }, vo);
    },
    addGroup() {
      this.showPop()
    },
    setEditvo(key) {
      let vo = this.$store.state.global.editVo
      vo[key] = this[key];
      util.store.commit(this,'setEditVo', vo)
    },
    hlChange() {},
    onMove({
      relatedContext,
      draggedContext
    }) {
      const relatedElement = relatedContext.element;
      const draggedElement = draggedContext.element;
      let rl = relatedContext.list.length
      let reTitle = relatedElement ? relatedElement.title : ''
      if (rl == 1 && reTitle == '占位（请忽略）') {
        // tool.cl('fff')
        relatedContext.list.splice(0, 1)
      }
      // tool.cl(relatedContext, draggedContext)
      return true
    },
    showBigPic(img) {
      tool.cl(img)
    },
    zipLoad(attr) {
      if(this.inner_filtered) {
        this.filter_attr(attr)
      }else{
        util.mywait(this, 'inner_filtered', () => {
          this.filter_attr(attr)
        });
      }
    },
    zipRemoved(removed) {
      this.attr.push(removed)
    },
    zipChange(_id) {
      this.attr = this.attr.filter(item => {
        return item.id != _id
      });

      this.attr_group = this.attr_group.map(arr => {
        // let ids=util.getObjArrAttr(arr,'id')
        return arr.filter(item => {
          return item.id != _id
        })
      });
      this.pro_attr_group_str()
    },
    setList(pics) {
      let tmp = []
      if (pics.length > 0) {
        tmp = pics.map(val => {
          if (val)
            return IMGPRE + val
        })
      }
      this.plist = tmp || []
    },
    init2() {
      let l = this.attr_group.length

      let first = util.deepCopy(this.attr_group[0][0])

      this.attr_group[0] = []

      this.attr_group[0] = [first]
      this.attr_group[0][0].id = -1;
      this.attr_group[0][0].title = '占位（请忽略）';

      this.pro_attr_group_str()
    },
    group_init(fields, f) {
      let maped = fields.map(field => {
        return {
          id: field.id,
          name: field.name,
          title: field.title
        }
      })
      this.attr_group[0] = maped

      if (f) {
        this.pro_attr_group_str()
      } else {
        this.pro_attr_group_str()
        this.pro_group_str()
      }

    }
  },
  watch: {
    v: function(val, old) {
      //        tool.cl(val, old)
      if (val != old) {

        this.val = val
      }

    },
    attr: function(val, old) {
      if (val != old) {
        // tool.cl(val)
        // this.setList(val)
      }
    },
    tab_title: function(val, old) {
      if (val) {
        this.pro_tab_title_str()
      }
    },
    group: function(val, old) {
      if (val) {
        this.pro_group_str()
      }
    },
    attr_group: function(val, old) {
      if (val) {

        this.pro_attr_group_str()

      }
    },
    isDragging(newValue) {
      if (newValue) {
        this.delayedDragging = true
        return
      }
      this.$nextTick(() => {
        this.delayedDragging = false
      })
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 0,
        group: 'description',
        disabled: !this.editable,
        ghostClass: 'ghost'
      };
    },
    placeholder() {
      return `请输入${this.field.title}`
    },
  },
  props: ['field', 'mid'],
  created() {
    util.getBindField(this, this.mid, 0, (fields) => {
      if (fields) {
        this.attr = fields
        if (this.$store.state.global.op == 'update') {
          let vo = this.$store.state.global.editVo

          let group_str = vo.group_str
          if (group_str && group_str != '[]') {
            this.group = JSON.parse(group_str)
            if(vo.tab_title_str)
              this.tab_title = JSON.parse(vo.tab_title_str)
            this.pro_group_str()

            if (vo.attr_group_str && vo.attr_group_str != '[]') {
              let tmp = {}
              fields.forEach(field => {

                tmp[field.id] = {
                  id: field.id,
                  name: field.name,
                  title: field.title
                }

              })
              // tool.cl(tmp)

              let attr_group = JSON.parse(vo.attr_group_str)
              this.attr_group = attr_group.map(group => {
                group = group.filter((id) => {
                  return tmp[id]
                })
                return group.map(id => {
                  return {
                    id: id,
                    name: tmp[id].name,
                    title: tmp[id].title
                  }
                })
              })

              this.pro_attr_group_str()


            } else {
              this.group_init(fields, 1)
            }
          } else {
            this.group_init(fields)
          }

        } else {
          this.group_init(fields)
        }

        if (this.$store.state.global.op !== 'update')
          this.init2()
        else {
          this.filter_attr()
        }

        this.show = true
      }
    });

    let eventVue = util.store.get(this,'eventVue');
    eventVue.$on('toAddAttrGroup', this.toAddAttrGroup)
    eventVue.$on('zipChange', this.zipChange)
    eventVue.$on('zipLoad', this.zipLoad)
    eventVue.$on('zipRemoved', this.zipRemoved)
  },
  destroyed() {
    let eventVue = util.store.get(this,'eventVue');
    eventVue.$off('toAddAttrGroup', this.toAddAttrGroup)
  },
  mounted() {}
};
</script>

<style rel="stylesheet/less" lang="less" scoped>@import "../../common/style/mixin";
@dir: "edit/";

.flip-list-move {
    transition: transform 0.5s;
}

.ui.vertical.menu {
    display: inline-block;
    vertical-align: top;
    margin-left: 10px;

}

.attrGroupWrapper {
  .sortMenu();
}
</style>
